package com.hualan.utils;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class ExecUtil {
    private static PreparedStatement preparedStatement;
    private static Connection conn;
    public static Object execute(String sql, List<Object> params, HttpServletRequest req, Boolean update)  {
        //获取链接对象
        conn = (Connection) req.getAttribute("conn");
        try {
            //创建SQL预处理对象
            ExecUtil.preparedStatement = conn.prepareStatement(sql);
            //向sql语句中添加对应的数据
            for(Integer i = 0; i < params.size(); i++){
                preparedStatement.setObject(i+1, params.get(i));
            }
            if(update){
                preparedStatement.executeUpdate();
                return true;
            }else{
                ResultSet resultSet = preparedStatement.executeQuery();
                return resultSet;
            }
        }catch (Exception e){
            System.out.println("数据库操作异常");
            return e;
        }
    }

    public static void close() throws SQLException {
        ExecUtil.preparedStatement.close();
    }
    public static void commit() {
        //提交执行结果
        try {
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void rollback(){
        //回滚操作
        try {
            conn.rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
